import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from sympy import symbols, limit, sin, exp, log

# 中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def instantaneous_velocity():
    """
    使用极限概念计算瞬时速度
    假设位移函数 S(t) = t^3 - 2t^2 + 3t + 1
    求t=2时的瞬时速度
    """
    t = symbols('t')
    S = t**3 - 2*t**2 + 3*t + 1  # 位移函数
    
    # 瞬时速度 = lim(Δt→0)[S(t+Δt) - S(t)]/Δt
    Δt = symbols('Δt')
    t0 = 2
    
    # 平均速度
    S_t0 = S.subs(t, t0)
    S_t0_plus_Δt = S.subs(t, t0 + Δt)
    average_velocity = (S_t0_plus_Δt - S_t0) / Δt
    
    # 瞬时速度（极限）
    instantaneous_vel = limit(average_velocity, Δt, 0)
    
    print("瞬时速度计算示例:")
    print(f"位移函数 S(t) = {S}")
    print(f"在 t = {t0} 时的位移 S({t0}) = {S_t0}")
    print(f"平均速度表达式: [S({t0}+Δt) - S({t0})]/Δt = {average_velocity}")
    print(f"瞬时速度: lim(Δt→0)平均速度 = {instantaneous_vel}")
    
    # 可视化
    Δt_vals = np.linspace(0.1, 1, 50)
    avg_vel_vals = []
    for dt in Δt_vals:
        avg_vel = (S.subs(t, t0+dt) - S_t0) / dt
        avg_vel_vals.append(avg_vel)
    
    plt.figure(figsize=(10, 6))
    plt.plot(Δt_vals, avg_vel_vals, 'bo-', linewidth=2, markersize=4, 
             label='平均速度')
    plt.axhline(y=instantaneous_vel, color='r', linestyle='--', linewidth=2,
                label=f'瞬时速度 = {instantaneous_vel}')
    plt.xlabel('时间间隔 Δt')
    plt.ylabel('速度')
    plt.title('平均速度随Δt变化及瞬时速度极限')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.show()

instantaneous_velocity()